#By Daoyu @2010-07-28

from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.template import RequestContext

from uncle.users.models import *
from uncle.util.page import *

#-------------------------------------------------------------------------------
# Add a video to a basket.
#-------------------------------------------------------------------------------
def add(request):
    if request.user.has_perm('users.is_producer'):
        bv = Basket_video()
        bas = Basket.objects.get(id=request.POST['basket'])
        v = video.objects.get(id=request.POST['v_id'])
        bv.film = v
        bv.basket = bas
        
        bv.save()        

#-------------------------------------------------------------------------------
# Manage the basket of a user.
#-------------------------------------------------------------------------------
def manage(request):
    if request.method=='GET':
        baskets = Basket.objects.filter(user__id=request.user.id)
        dicts = {}
        for bas in baskets:
            dicts[bas] = [ x for x in Basket_video.objects.filter(basket = bas)]
        basket = None
        if dicts:
            basket = baskets[0]
        
        return render_to_response('user/basket.html',
              {'dicts':dicts,'basket':basket,},
              context_instance = RequestContext(request))
    elif request.method=='POST':
        basket = Basket()
        basket.user = request.user
        basket.name = request.POST['new_basket']
        
        basket.save()
        
        request.user.message_set.create(
            message = 'New basket added.')
        
        return HttpResponseRedirect('/user/basket/')
    
#-------------------------------------------------------------------------------
# Delete the basket's video object.
#-------------------------------------------------------------------------------
def delete_basket_video(request, b_v_id):
    if request.user.has_perm('users.is_producer'):
        Basket_video.objects.filter(id = b_v_id).delete()
        request.user.message_set.create(message = 'Video deleted from basket.')
        
    return HttpResponseRedirect('/user/basket/')


def delete_basket(request,b_id):
    if request.user.has_perm('users.is_producer'):
        Basket.objects.filter(id = b_id).delete()
        request.user.message_set.create(message = 'Basket deleted')
    return HttpResponseRedirect('/user/basket/')
